package org.colcon.web.client.ui;

import org.colcon.web.client.Collective_Congress;
import org.colcon.web.model.framework.IContainer;
import org.colcon.web.model.framework.IItem;
import org.colcon.web.model.parsers.CLIParser;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ListPanel extends ItemPanel
{
	private final Label loading = new Label("Loading...");
	
	public ListPanel(Collective_Congress client, String item)
	{
		this(client, (IContainer) CLIParser.parseItem(item));
	}
	
	public ListPanel(Collective_Congress client, IContainer container) 
	{
		super(client, container);
		
		add(loading);
		
		final String path = container.getPath();
		
		getService().open(path, new AsyncCallback<String[]>()
		{
			public void onFailure(Throwable caught)
			{
				remove(loading);
				getBodyPanel().add(new Label("failed to open container '" + path + "'"));
			}
			
			public void onSuccess(String[] array)
			{
				remove(loading);
				
				VerticalPanel panel = new VerticalPanel();
				ScrollPanel scroll = new ScrollPanel(panel);
				
				panel.setWidth("100%");
				scroll.setHeight("500px");
				
				for(String str : array)
				{
					IItem item = CLIParser.parseItem(str);
					
					if(item != null)
						panel.add(new HTML("<pre>" + item.getText() + "</pre>"));
				}
				
				add(scroll);
			}
		});
	}
	
	public IContainer getContainer()
	{
		return (IContainer) getItem();
	}
}
